package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"strconv"
)

type Step struct {
	Id    int64  `json:"id"`
	Name  string `json:"name"`
	Code  string `json:"code"`
	Color string `json:"color"`
}

type stepRelation struct {
	Step
	ParentIdString string `json:"parent_id"`
	ParentId       int64
}

type StepWithChildren struct {
	Step
	Children []StepWithChildren `json:"children"`
}

type StepWithParent struct {
	Step
	Parent []*StepWithParent `json:"parent"`
}

type StepParentResItem struct {
	Step
	Level int
}

func findParent(stepParentMap map[int64]*StepWithParent, findIdList []int64, parent *[]StepParentResItem, level int, maxLevel int) {

	if maxLevel > 0 && level == maxLevel || len(findIdList) == 0 {
		return
	}
	var nextFindIdList = make([]int64, 0)

	for _, i := range findIdList {
		if _, ok := stepParentMap[i]; !ok {
			continue
		}
		if len(stepParentMap[i].Parent) > 0 {
			for _, withParent := range stepParentMap[i].Parent {
				*parent = append(*parent, StepParentResItem{
					Step: Step{
						Id:    withParent.Id,
						Name:  withParent.Name,
						Code:  withParent.Code,
						Color: withParent.Color,
					},
					Level: level,
				})
				nextFindIdList = append(nextFindIdList, withParent.Id)
			}
		}

	}
	if len(nextFindIdList) > 0 {
		findParent(stepParentMap, nextFindIdList, parent, level+1, maxLevel)
	}

}

func main() {

	jsonraw, err := ioutil.ReadFile("./Result_7.json")
	if err != nil {
		log.Fatal(err.Error())
	}

	var stepRelationList []stepRelation

	_ = json.Unmarshal(jsonraw, &stepRelationList)
	var stepMap = make(map[int64]bool, 0)
	var stepWithParentList = make([]StepWithParent, 0)

	var stepWithParentMap = make(map[int64]*StepWithParent)

	for k, s := range stepRelationList {
		parentId, err := strconv.ParseInt(s.ParentIdString, 10, 0)
		if err != nil {
			parentId = 0
		}
		stepRelationList[k].ParentId = parentId
		if _, ok := stepMap[s.Id]; !ok {
			stepMap[s.Id] = true
			stepWithParentList = append(stepWithParentList, StepWithParent{
				Step: Step{
					Id:    s.Id,
					Name:  s.Name,
					Code:  s.Code,
					Color: s.Color,
				},
			})
		}
	}

	//  制造一个steplist的map
	for i, v := range stepWithParentList {
		stepWithParentMap[v.Id] = &stepWithParentList[i]
	}

	for _, s := range stepRelationList {
		if s.ParentId > 0 {
			stepWithParentMap[s.Id].Parent = append(stepWithParentMap[s.Id].Parent, stepWithParentMap[s.ParentId])
		}
	}

	println(jsonraw)

	var parentRes = make([]StepParentResItem, 0)

	findParent(stepWithParentMap, []int64{64}, &parentRes, 0, 0)

	println(1)
}
